package com.fs.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fs.mapper.OrderGoodsMapper;
import com.fs.mapper.OrderMapper;
import com.fs.mapper.UserAddrMapper;
import com.fs.pojo.Order;
import com.fs.vo.PageResult;
import com.fs.vo.SysResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService{

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderGoodsMapper orderGoodsMapper;

    @Autowired
    private UserAddrMapper userAddrMapper;

    @Override
    public SysResult getList(PageResult pageResult) {
        if (pageResult == null) return SysResult.fail();

        int pageNum = pageResult.getPageNum();
        int pageSize = pageResult.getPageSize();

        if (pageNum < 1) pageNum = 1;
        if (pageSize < 1) pageSize = 10;

        Page<Order> page = new Page<>(pageNum, pageSize);


        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(pageResult.getQuery()), "username", pageResult.getQuery())
                .orderByDesc("id");
        page = orderMapper.selectPage(page, queryWrapper);

        int offset=(pageNum-1)*pageSize;

        pageResult.setTotal(orderMapper.getTotal()).setRows(orderMapper.getList(offset,pageSize));

        return SysResult.success(pageResult);
    }

    @Override
    public SysResult getById(Integer id) {
        Map<String,Object> order = orderMapper.getById(id);
        List<Map<String,String>> orderGoods = orderGoodsMapper.selectByOrderId(id);
        HashMap<String, Object> back = new HashMap<>();
        back.put("order", order);
        back.put("detail", orderGoods);
        System.out.println(back);
        return SysResult.success(back);
    }

    @Override
    @Transactional
    public SysResult updateRev(Integer id, Integer s) {
        Order order = new Order();
        order.setId(id).setReceiving(s).setUpdated(new Date());
        orderMapper.updateById(order);
        return SysResult.success();
    }
}
